package com.blackcat.recode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blackcat.recode.common.result.AjaxResult;
import com.blackcat.recode.entity.Branch;
import com.blackcat.recode.entity.Customer;
import com.blackcat.recode.dao.CustomerMapper;
import com.blackcat.recode.entity.DeployVo;
import com.blackcat.recode.service.CustomerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blackcat.recode.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * <p> 客户信息表 服务实现类
 * @author blackcat 2024-09-10
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public AjaxResult getCustomerNameList() {
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "customer_name");
        return AjaxResult.success(customerMapper.selectList(queryWrapper));
    }

    @Override
    public AjaxResult getAllCustomerList() {
        List<Customer> result = new ArrayList<>();
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("customer_name");
        List<Customer> customerList = customerMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(customerList)) {
            customerList.forEach(i -> {
                List<DeployVo> deployVoList = customerMapper.selectDeployList(i.getId());
                if (CollectionUtils.isNotEmpty(deployVoList)) {
                    i.setDeployList(deployVoList);
                    result.add(i);
                }
            });
        }
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult getList(Integer pageNow, Integer pageSize, String customerName) {
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(customerName)) {
            queryWrapper.like("customer_name", customerName);
        }
        queryWrapper.orderByAsc("customer_name");
        Page<Customer> page = new Page<>(pageNow, pageSize);
        Page<Customer> result = customerMapper.selectPage(page, queryWrapper);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult edit(Customer customer) {
        if (customer.getId() == null) {
            customerMapper.insert(customer);
        }else {
            customerMapper.updateById(customer);
        }
        return AjaxResult.success();
    }
}
